const crypto = require('crypto')
const urlParser = require('url')

const utils = {}

utils.genSHA1 = function (content) {
    return utils.genHash(content, 'sha1')
}

utils.genHash = function (content, algorithm) {
    const c = crypto.createHash(algorithm)
    c.update(content, 'utf8')
    return c.digest('hex')
}

utils.nonceStr = function () {
    return Math.random()
        .toString(36)
        .substr(2, 15);
}

utils.timestamp = function () {
    return parseInt(new Date().getTime() / 1000) + '';
};

utils.paramsToString = function (args, noLowerCase) {
    let keys = Object.keys(args);
    keys = keys.sort();
    const newArgs = {};
    keys.forEach(key => {
        const temp = noLowerCase ? key : key.toLowerCase();
        newArgs[temp] = args[key];
    });

    let str = '';
    for (let k in newArgs) {
        if (newArgs.hasOwnProperty(k)) {
            str += '&' + k + '=' + newArgs[k];
        }
    }
    str = str.substr(1);
    return str;
}

utils.normalizeUrl = function (url) {
    const temp = urlParser.parse(url);
    const hashIndex = url.indexOf(temp.hash);
    // 去掉#及其后面部分
    return hashIndex > 0 ? url.substring(0, hashIndex) : url;
  }

module.exports = utils